package net.huashitong.oversee.JobTask;


import com.sirdc.modules.utils.ObjectUtils;
import com.sirdc.modules.utils.StringUtils;
import com.yunpian.sdk.YunpianClient;
import com.yunpian.sdk.model.Result;
import com.yunpian.sdk.model.SmsSingleSend;
import net.huashitong.node.entity.NodeNewschedules;
import net.huashitong.node.service.NodeNewschedulesService;
import net.huashitong.oversee.entity.SupervisionLog;
import net.huashitong.oversee.entity.SupervisionTask;
import net.huashitong.oversee.filter.SupervisionTaskFilter;
import net.huashitong.oversee.filter.TaskLogFilter;
import net.huashitong.oversee.service.FeedBackLeaderService;
import net.huashitong.oversee.service.GradePointService;
import net.huashitong.oversee.service.SupervisionLogService;
import net.huashitong.oversee.service.SupervisionTaskService;
import net.huashitong.user.entity.BnpUser;
import net.huashitong.user.entity.Message;
import net.huashitong.user.service.BnpUserService;
import net.huashitong.user.service.MessageService;
import net.huashitong.utils.UtilsTools;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
public class JobTaskService {

    private static Logger log = LoggerFactory.getLogger(JobTaskService.class);


    @Autowired
    private SupervisionTaskService taskService;
    @Autowired
    private SupervisionLogService missionlogservice;
    @Autowired
    private GradePointService gradeService;
    @Autowired
    private MessageService ms;
    @Autowired
    private FeedBackLeaderService feedService;
    @Autowired
    private NodeNewschedulesService nodeNewschedulesService;

    @Autowired
    private BnpUserService bnpUserService;

    /**
     * 判断未完成的任务是否到期。 自动保存分数。
     */
    public void saveSourceExpire() throws ParseException {
        log.info("----------- 督查排查任务开始-----------");
        SupervisionTaskFilter filter = new SupervisionTaskFilter();
        TaskLogFilter logfilter = new TaskLogFilter();
        filter.setTaskResult("0");  // 所有未完成的任务
        filter.setValid("1"); //有效任务
        List<SupervisionTask> taskList = taskService.getTaskLists(filter);
        String msg = null;
        String record = null;
        for (SupervisionTask items : taskList) {
            Date EndDate, currentDate;
            try {
                //督查轮数
                String taskTimes = items.getTasktimes();
                int taskTimesInt = Integer.parseInt(taskTimes);

                EndDate = UtilsTools.StringToDate(items.getPlanEndDate());//计划结束时间，
                currentDate = UtilsTools.StringToDate(UtilsTools.getCurrentDate());//当前日期
                int flag = EndDate.compareTo(currentDate); //计划结束时间和当前时间比较。是否到期。
                if (flag == 0) {
                    //加个短信提醒






                    log.info(UtilsTools.getCurrentDate() + "---是您任务最后一天，请及时完成--");
                } else if (flag < 0) {
                    log.info("---超时了。 反馈攻坚办-----");
                    items.setIsfeedback("1"); //1 反馈给攻坚办。
                    // logfilter.setTaskId(items.getSysId());
                    List<SupervisionLog> logs = missionlogservice.getMissionLog(items.getSysId());
                    if (ObjectUtils.isBlank(logs)) {
                        log.info("------------无催办记录-----------");
                        record = "【无任何】";
                    } else {
                        record = "【有" + logs.size() + "条】";
                    }
                    msg = "【重大项目节点管理】您好!督查任务:" + items.getTaskName() + ",任务结果:未完成,该督查组" + record + "督查催办记录.督查小组为:" + items.getGroupType() + ",责任单位为:" + items.getResDept() + ",请及时处理。系统地址：https://www.fzzhengxinyun.com ，帐号为个人手机号，初始密码123456";
                    String[] phoneArr = items.getPhones().split(",");
                    String[] inspector = items.getInspectors().split(",");

                    for (int i = 0; i < phoneArr.length; i++) {
                        YunpianClient clnt = new YunpianClient(UtilsTools.msgapiKey).init();
                        //修改账户信息API
                        Map<String, String> param = clnt.newParam(2);
                        param.put(YunpianClient.MOBILE, phoneArr[i]);
                        param.put(YunpianClient.TEXT, msg);
                        Result<SmsSingleSend> r = clnt.sms().single_send(param);
                        log.info("------------" + r.getMsg() + "----------");
                        clnt.close();
                        Message m = new Message();
                        m.setRecipients(inspector[i]);
                        m.setText(msg);
                        m.setType("9");
                        m.setPhone(phoneArr[i]);
                        m.setMsg(msg);
                        m.setProjectName(items.getProjectName());
                        m.setResDept(items.getResDept());
//                        m.setNodeId(ewn.getNodeSysId());
                        m.setState("0");
                        ms.save(m);

                    }

                    //---------督查组 进入绩效评分。-----------
                    gradeService.saveGroupSocure(items);
                    //------- 业主单位和审批单位经办人的绩效考核 ---------
                    gradeService.saveGroupScoreInOperator(items);
                    //------- 业主单位和审批单位责任人的绩效考核 ---------
                    gradeService.saveGroupScoreInResUer(items);

                    if (Integer.parseInt(items.getTasktimes()) == 3) {
                        items.setEndDate(UtilsTools.getCurrentDate());
                        items.setTackFlag("1");                 //设置成攻坚任务
                        items.setTackTaskType("自动生成");      //设置自动生成
                        items.setTaskResult("3");               //已经考评有结果了。
                        taskService.update(items);
                        continue;
                    }

                    //开启下一轮督查任务
                    String projectId = items.getProjectId();
                    String nodeId = items.getNodeId();
                    NodeNewschedules nodeNewschedules = nodeNewschedulesService.getNodeNewschedulesByProjectIdAndNodeId(projectId, nodeId);
                    String planTime = nodeNewschedules.getPlanTime();
                    int planTimeInt = Integer.parseInt(planTime);
                    int taskDate = 1;       //督查时间设置
                    if (!(planTimeInt == 0 || planTimeInt == 1)) {
                        taskDate = planTimeInt / 2;
                        int remainder = planTimeInt % 2;         //取余数
                        if (remainder != 0) {
                            taskDate = taskDate + 1;
                        }
                    }
                    if (taskDate > 15) {
                        taskDate = 15;
                    }
                    items.setTaskDate(taskDate + "");
                    //计划开始时间
                    items.setPlanStartDate(UtilsTools.getCurrentDate());
                    //计划结束时间
                    items.setPlanEndDate(UtilsTools.plusDay(taskDate, UtilsTools.getCurrentDate()));
                    //实际开始时间（同上）
                    items.setStartDate(UtilsTools.getCurrentDate());
                    //实际结束时间（默认为空）
                    items.setEndDate(null);
                    //督查次数加1
                    taskTimesInt = taskTimesInt + 1;
                    items.setTasktimes(taskTimesInt + "");
                    items.setAaa002("0");           //设置未发送短信，后台重新发送提醒短信
                    taskService.update(items);
                }
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }


        //========================================================================
        SupervisionTaskFilter filter9 = new SupervisionTaskFilter();
        filter9.setTaskResult("1");  // 所有已完成的任务
        filter9.setValid("1"); //有效任务
        List<SupervisionTask> lists = taskService.getTaskLists(filter9);
        for (SupervisionTask task : lists) {
            gradeService.saveGroupSocure(task);
            gradeService.saveGroupScoreInOperator(task);
            gradeService.saveGroupScoreInResUer(task);
        }

        SupervisionTaskFilter filter10 = new SupervisionTaskFilter();
        filter10.setTaskResult("1");  //所有已完成的任务（攻坚）
        filter10.setValid("1");     //有效任务
        filter10.setTackFlag("3"); //攻坚
        List<SupervisionTask> list10 = taskService.getTaskLists(filter10);
        for (SupervisionTask task : list10) {
            gradeService.saveGroupSocure(task);
            gradeService.saveGroupScoreInOperator(task);
            gradeService.saveGroupScoreInResUer(task);
        }


    }

    /**
     * 定时发短信通知督查组和责任单位
     */
    public void sendMsgToTM() {
        List<SupervisionTask> tasks = taskService.getNotSendMsg();

        for (SupervisionTask item : tasks) {
            //督查组手机号
            String[] phones = item.getPhones().split(",");
            //督查组人员
            String[] inspector = item.getInspectors().split(",");
            String[] groupType = item.getGroupType().split(",");
            for (int i = 0; i < phones.length; i++) {
                int codeducha = feedService.sendMsgToDuchaAndDept(item.getProjectName(),
                        item.getSysId(),
                        item.getTaskName(), phones[i]);
                Message m = new Message();
                m.setProjectName(item.getTaskName());
                m.setResDept(groupType[i]);
                m.setRecipients(inspector[i]);
                m.setPhone(phones[i]);
                m.setType("9");
                m.setText("督查任务单单号:" + item.getSysId() + ",任务详情请到督查任务菜单查看!");
                m.setBranchType("4");
                ms.save(m);
            }
            //经办人发短信
            int codejingban = feedService.sendMsgToDuchaAndDept(item.getProjectName(), item.getSysId(), item.getTaskName(), item.getOperatorPhone()/*"18350300651"*/);
            Message m = new Message();
            m.setProjectName(item.getTaskName());
            m.setResDept(item.getResDept());
            m.setRecipients(item.getOperatorUser());
            m.setPhone(item.getOperatorPhone());
            m.setType("9");
            m.setText("督查任务单单号:" + item.getSysId() + ",任务详情请到督查任务菜单查看!");
            BnpUser user = bnpUserService.getBnpUserByPhoneAndName(item.getOperatorPhone(), item.getOperatorUser());
            if (ObjectUtils.isNotBlank(user)) {
                m.setBranchType(user.getBranchType());
            }
            ms.save(m);
            //责任人
            int codezeren = feedService.sendMsgToDuchaAndDept(item.getProjectName(), item.getSysId(), item.getTaskName(), item.getResPhone()/*"18259269331"*/);
            m = new Message();
            m.setResDept(item.getResDept());
            m.setProjectName(item.getTaskName());
            m.setRecipients(item.getResUser());
            m.setPhone(item.getResPhone());
            m.setType("9");
            m.setText("督查任务单单号:" + item.getSysId() + ",任务详情请到督查任务菜单查看!");
            if (ObjectUtils.isNotBlank(user)) {
                m.setBranchType(user.getBranchType());
            }
            ms.save(m);
            item.setAaa002("1");
            taskService.update(item);
        }
    }


//    public void saveOwnerScore(){
//        log.info("-----------考评业主单位开始-----------");
//        SupervisionTaskFilter filter = new SupervisionTaskFilter();
//        filter.setTaskResult("0");              // 所有未完成的任务
//        filter.setValid("1");                   //有效任务
//        List<SupervisionTask> taskList = taskService.getTaskLists(filter);
//        for(SupervisionTask items : taskList){
//            String operatorUser = items.getOperatorUser();
//            String operatorPhone = items.getOperatorPhone();
//            BnpUser bnpUser = bnpUserService.getBnpUserByPhoneAndName(operatorPhone,operatorUser);
//            //判断是否是业主单位
//            if("0".equals(bnpUser.getBranchType())&&"经办人".equals(bnpUser.getRole())){
//
//            }
//        }
//
//    }
}
